/*
 * @Author: zlc
 * @Date: 2022-07-12 09:02:16
 * @LastEditTime: 2022-07-25 15:50:06
 * @LastEditors: zlc
 * @Description: 用户数据相关
 * @FilePath: \teachernotice\store\user\user.js
 * setStorage：默认是存放本地，不在需要使用后，应及时清空
 */
import {
	ALL_USERS_SUCCESS,
	ALL_INFOANDCLASS_SUCCESS
} from '@/store/user/mutaion-type.js'
import {
	setStorage,
	getStorage
} from '@/common/util/storage.js'
import api from '@/common/api.js'
export default {
	state: {
		//用户数据（登录标识）
		userInfo: getStorage('userInfo') || {
			userProfile: {}, //用户头像
			wxUserId: {}, //用户unionid
			jxyUserInfo: {}, //用户token，根据token/unionid来判断是否已经登录,
		},
		//教师数据
		infoAndClass: getStorage('infoAndClass') || {}
	},

	mutations: {
		/**
		 * @description: 存放用户信息
		 * @param {Object} state 
		 * @param {Object} payload.userProfile 用户头像
		 * @param {Object} payload.wxUserId unionid、openID
		 * @param {Object} payload.jxyUserInfo 用户token，唯一标识，登录后下存放
		 * @return {Object} 解密后用户数据
		 * 接口协定：每次登录后数据更新一次，登录后使用教师数据应是infoAndClass，而不是userInfo（只是用来判断登录状态/openId/unionid）
		 * userInfo所有数据进行加解密-延期至7.15
		 */
		[ALL_USERS_SUCCESS](state, payload = {}) {
			for (let i in payload) {
				if (state.userInfo[i] !== undefined) {
					state.userInfo[i] = payload[i];
				}
			}
			setStorage('userInfo', state.userInfo)
		},
		/**
		 * @description: 存放老师数据教师名称、学校、班级等
		 * @param {Object} state 
		 * @param {Object} payload.infoAndClass 
		 * @return {*} 
		 * 后台每次更新后infoAndClass应存放最新的数据
		 */
		[ALL_INFOANDCLASS_SUCCESS](state, payload) {
			state.infoAndClass = payload.infoAndClass
			setStorage('infoAndClass', state.infoAndClass)
		},
	},

	actions: {
		/**
		 * @description: 用于用户已登录后的后续用户信息更新
		 * @param {Function} commit
		 * @param {Object} state
		 * @return {*}
		 */
		updateJxyUserInfo({
			commit,
			state
		}, payload) {
			return new Promise(async (reslove, reject) => {
				let res1;
				try {
					res1 = await api.user.get_info()
				} catch (err) {
					reject(err)
					return
				}
				const token = state.userInfo.jxyUserInfo.token;
				commit('ALL_USERS_SUCCESS', {
					jxyUserInfo: {
						...res1.result,
						token
					}
				})
				reslove()
			})
		},
		/**
		 * @description: 获取教师数据
		 * @param {Function} commit
		 * @param {Object} state
		 * @param {String} payload.phone 手机号
		 * @return {*}
		 */
		getUserInfoAndClass({
			commit,
			state
		}, payload) {
			return new Promise((resolve, reject) => {
				api.user.get_user_squad_info({
						phone: state.userInfo.jxyUserInfo.phone
					}).then(res => {
						commit('ALL_INFOANDCLASS_SUCCESS', {
							infoAndClass: res.result
						})
						resolve(res)
					})
					.catch((err) => {
						reject(err)
					})
			})
		}
	},
}
